﻿using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace TableCore
{
    public partial class GTFile
    {
        readonly Regex VALID_CLASS_NAME = new Regex("[A-Za-z_]+[a-zA-Z0-9_]*");
        readonly Regex USING_NAMESPACE = new Regex(@"%USING_NAMESPACE%");
        readonly Regex CLASS_NAME = new Regex(@"%CLASS_NAME%");
        readonly Regex PROPERTY_DEFINE = new Regex(@"%PROPERTY_DEFINE%");
        readonly Regex INDEX_DEFINE = new Regex(@"%PROPERTY_INDEX%");
        readonly Regex PROPERTY_DESERIALIZE = new Regex(@"%PROPERTY_DESERIALIZE\([a-zA-Z_0-9]+\)%");
        readonly Regex SERIALIZATION_ID = new Regex(@"%SERIALIZATION_ID%");
        readonly Regex CLONE = new Regex(@"%CLONE\([a-zA-Z_0-9]+\)%");

        string mCodeTemplate;
        List<string> mDefaultNamespace;
        string mCodeLineEnding;

        void InitCodeTemplate(string file)
        {
            mCodeTemplate = File.ReadAllText(file/*, System.Text.Encoding.UTF8*/).Replace("%INPUT%", "data");
            var namespaceUsing = Regex.Matches(mCodeTemplate, @"(?<=using +)[a-zA-Z_]+[a-zA-Z_0-9]*(\.[a-zA-Z_]+[a-zA-Z_0-9]*)*(?= *;)");
            if (namespaceUsing != null && namespaceUsing.Count > 0)
            {
                mDefaultNamespace = new List<string>(namespaceUsing.Count);
                for (int i = 0; i < namespaceUsing.Count; i++)
                {
                    var match = namespaceUsing[i];
                    mDefaultNamespace.Add(match.Value);
                }
            }
            var n = mCodeTemplate.IndexOf('\n');
            if (n > 0 && mCodeTemplate[n - 1] == '\r')
                mCodeLineEnding = "\r\n";
            else
                mCodeLineEnding = "\n";
        }

        string GetSpaceBefore(string str, int end)
        {
            if (end <= str.Length)
            {
                for (int i = end - 1; i >= 0; i--)
                {
                    var c = str[i];
                    if (c != ' ' && c != '\t')
                    {
                        return end > i + 1 ? str.Substring(i + 1, end - i - 1) : "";
                    }
                }
            }
            return "";
        }

        string GetArgName(string function)
        {
            var n1 = function.IndexOf('(');
            var n2 = function.IndexOf(')', n1+1);
            return n1 > 0 && n2 > n1 ? function.Substring(n1 + 1, n2 - n1 - 1) : "arg";
        }

    }
}
